package com.witframework.core.errorhandling;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * <P>
 * web 应用异常处理器， 异常信息记录入日志文件。
 * </P>
 * @author wuxinyang
 *
 */
public class DefaultWARExceptionHandler{
	static Map<String, String> localMsg=new HashMap<String, String>();
	Log log = LogFactory.getLog(DefaultWARExceptionHandler.class);
	private Throwable e;
	static{
		localMsg.put("could not delete","不能删除数据");
		localMsg.put("ConstraintViolationException","违反了约束");
		localMsg.put("HibernateOptimisticLockingFailureException","数据在此操作前已被更改。");
		localMsg.put("Cannot delete or update a parent row: a foreign key constraint fails","存在子数据项(已被其他数据引用)");
	}
    public DefaultWARExceptionHandler(Throwable e) {
    	this.e=e;
    	//log.error(e);
    	e.printStackTrace();
    }
    public String getMessage() {    	
    	ByteArrayOutputStream bos=new ByteArrayOutputStream(1024);
    	e.printStackTrace(new PrintStream(bos,true));
    	String msg;
		try {
			msg = bos.toString("utf-8");
		} catch (UnsupportedEncodingException e1) {
			msg=new String(bos.toByteArray());
		}
    	for(String s:localMsg.keySet()){
    		if(msg.indexOf(s)>=0)
    			return localMsg.get(s);
    	}
    	return e.getLocalizedMessage();
    }

}

